﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.SuperGrid;
using DevComponents.DotNetBar.SuperGrid.Style;
using Platform.Model;
using Platform.Model.Repositories;
using PlatformManagement.Properties;
using BLToolkit.Data;
using Platform.Utilities;
using System.Text.RegularExpressions;

namespace PlatformManagement
{
    public partial class PackageForm : DevComponents.DotNetBar.Metro.MetroForm
    {
        bool _currentDerty = false;
        public PackageForm()
        {
            InitializeComponent();
            dgvPackage.AutoGenerateColumns = false;
        }


		protected override void OnActivated(EventArgs e)
		{
			base.OnActivated(e);
			this.WindowState = FormWindowState.Maximized;
		}
        // Load dữ liệu từ Database lên form
		protected override void OnLoad(EventArgs e)
		{
            dgvPackage.DataSource = new BindingSource { DataSource = Package.Objects.ToList() };
            base.OnLoad(e);
		}

        /// <summary>
        /// Xóa Package được chọn
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            // Lấy những dòng được đánh dấu check
            var selectedRows = dgvPackage.Rows.Cast<DataGridViewRow>()
                    .Where(x => x.Cells[0].Value != null && x.Cells[1].Value != null && (bool)x.Cells[0].Value)
                    .ToList();
            if (selectedRows.Count == 0)
            {
                MessageBox.Show("Please select employee by checking on checkbox.", "Message",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            var message = "All selected employee and related data will be deleted forever. Are you sure?";

            // Xuất thông báo cho việc xóa
            if (MessageBox.Show(message, "Warning !!!", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                // Duyệt qua từng dòng được chọn
                for (int i = selectedRows.Count - 1; i >= 0; i--)
                {
                    int id = Convert.ToInt32(selectedRows[i].Cells[1].Value.ToString());
                    Package.Objects.DeleteByKey(id);

                }
                dgvPackage.DataSource = new BindingSource { DataSource = Package.Objects.ToList() };
            }
        }

        /// <summary>
        /// Sự kiện nhấn Enter lưu thay đổi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void dgvPackage_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (_currentDerty)
            {
                try
                {
                    var cur = dgvPackage.Rows[e.RowIndex];
                    var pck = Package.Objects.ToList();
                    bool kt = false;
                    for (int i = 0; i < pck.Count; i++)
                    {
                        if (pck[i].PckName == cur.Cells[2].Value.ToString())
                            kt = true;
                    }
                    if (cur.Cells[1].Value.ToString() == "0")
                    {
                        if (!kt)
                        {
                            var p = new Package
                            {
                                PckName = cur.Cells[2].Value.ToString(),
                                Net = float.Parse(cur.Cells[3].Value.ToString()),
                                NLoss = float.Parse(cur.Cells[4].Value.ToString()),
                                PLoss = float.Parse(cur.Cells[5].Value.ToString()),
                                LastUpdated = DateTime.Now
                            };
                            Package.Objects.Insert(p);
                        }
                        else
                        {
                            MessageBox.Show("PackageName value must be unique");
                        }
                        dgvPackage.DataSource = new BindingSource { DataSource = Package.Objects.ToList() };
                    }
                    else
                    {
                        if (!kt)
                        {
                            var p = new Package
                                        {
                                            Id = int.Parse(cur.Cells[1].Value.ToString()),
                                            PckName = cur.Cells[2].Value.ToString(),
                                            Net = float.Parse(cur.Cells[3].Value.ToString()),
                                            NLoss = float.Parse(cur.Cells[4].Value.ToString()),
                                            PLoss = float.Parse(cur.Cells[5].Value.ToString()),
                                            LastUpdated = DateTime.Now
                                        };
                            Package.Objects.Update(p);
                        }
                        else
                        {
                            MessageBox.Show("PackageName value must be unique");
                        }
                        dgvPackage.DataSource = new BindingSource { DataSource = Package.Objects.ToList() };
                    }

                }
                catch (Exception ex)
                {

                    MessageBox.Show("Error: " + ex.Message);
                }
            }
            _currentDerty = false;
        }

        private void dgvPackage_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {

            if (dgvPackage.IsCurrentRowDirty && e.ColumnIndex > 0)
            {
                var currentRow = dgvPackage.Rows[e.RowIndex];
                if (currentRow.Cells[2].Value == null || string.IsNullOrEmpty(currentRow.Cells[2].Value.ToString()) ||
                         currentRow.Cells[3].Value == null || currentRow.Cells[4].Value == null ||
                         currentRow.Cells[5].Value == null)
                {
                    MessageBox.Show("You have to enter value for all cells", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
                if (!IsNumber(currentRow.Cells[2].Value.ToString()))
                {
                    MessageBox.Show("Dữ liệu phải là số dương 1", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
                if (!IsNumber(currentRow.Cells[3].Value.ToString()))
                {
                    MessageBox.Show("Dữ liệu phải là số dương 2", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
                if (!IsNumber(currentRow.Cells[4].Value.ToString()))
                {
                    MessageBox.Show("Dữ liệu phải là số dương 3", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
            }

            _currentDerty = dgvPackage.IsCurrentRowDirty;

        }
        //Hàm kiểm tra dữ liệu là số dương
        private bool IsNumber(string a)
        {
            float b;
            var regex = float.TryParse(a, out b);
            return true;
        }

        private void PackageForm_Load(object sender, EventArgs e)
        {
        }

        private void dgvPackage_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Input data is incrrect format, data is number");
        }
        

    }
}